package cn.chrilwe.pigpig.im.listener.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

import cn.chrilwe.pigpig.im.config.ServerConfig;
import cn.chrilwe.pigpig.im.listener.LifecycleListener;
import cn.chrilwe.pigpig.im.model.RabbitModel;
import cn.chrilwe.pigpig.im.rabbit.common.RabbitEnum;
import cn.chrilwe.pigpig.im.rabbit.factory.RabbitSession;
import cn.chrilwe.pigpig.im.rabbit.factory.RabbitSessionFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * netty启动和结束监听器
 * @author chrilwe
 * 2020-8-11
 */
@Slf4j
public class ServerLifecycleListener implements LifecycleListener {

	ApplicationContext context;
	
	ServerConfig serverConfig;
	
	@Override
	public void start() {
		log.debug("==============start netty server=========");
	}

	@Override
	public void end() {
		//rabbit 消息中间件开始监听其他服务器的消息
		List<String> shards = serverConfig.getShards();
		if(shards != null && shards.size() > 0) {
			for (String shard : shards) {
				log.debug("============starting rabbit listen to server :"+shard+" message");
				startRabbitListener(shard);
			}
		}
		log.debug("===============netty server start succefully=======");
	}
	
	

	public void setContext(ApplicationContext context) {
		this.context = context;
	}

	protected void startRabbitListener(String shard) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				RabbitSessionFactory factory = context.getBean(RabbitSessionFactory.class);
				RabbitSession session = factory.openSession();
				RabbitModel m = new RabbitModel();
				m.setAutoAck(true);
				m.setAutoDelete(false);
				m.setCurrentConnectPrivate(false);
				m.setExchange(RabbitEnum.EXCHANGE.getName());
				m.setMap(null);
				m.setPersistence(true);
				m.setQueue(shard);
				m.setRoutingKey(shard);
				session.receive(m);
			}
			
		},"rabbit-server-message-thread").start();
	}

	public void setServerConfig(ServerConfig serverConfig) {
		this.serverConfig = serverConfig;
	}
}
